package com.nineclock.approve.resolver.impl;

import cn.hutool.json.JSONObject;
import com.nineclock.approve.resolver.ProcessNodeResolver;
import com.nineclock.approve.util.ActivitiUtils;
import org.activiti.bpmn.model.MultiInstanceLoopCharacteristics;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.UserTask;

import java.util.Arrays;

/**
 * 审批节点解析处理器
 */
public class ApproveNodeResolver extends ProcessNodeResolver {

    @Override
    public void addFlowNodeToActiviti(Process process, JSONObject currNode, JSONObject nextNode) {

        //创建任务节点
        UserTask userTask = new UserTask();
        userTask.setId(getNodeId(currNode));
        userTask.setName(currNode.getStr("name"));
        userTask.setCategory("1");//审批

        //会签 / 或签
        String multiApproveMode = currNode.getStr("multiApproveMode");
        if("1".equals(multiApproveMode)){ //会签
            MultiInstanceLoopCharacteristics loopCharacteristics = new MultiInstanceLoopCharacteristics();
            loopCharacteristics.setSequential(false);//并行处理
            loopCharacteristics.setInputDataItem("${"+ ActivitiUtils.USERS_PREFIX+currNode.getStr("nodekey")+"}");//并行处理参与人
            loopCharacteristics.setElementVariable("assignee"); //变量名

            userTask.setLoopCharacteristics(loopCharacteristics);
            userTask.setAssignee("${assignee}");//最终会被替换
        }else{ //或签
            String user = ActivitiUtils.USERS_PREFIX + currNode.getStr("nodeKey");
            userTask.setCandidateUsers(Arrays.asList("${"+user+"}"));
        }

        process.addFlowElement(userTask);
        newSequenceFlow(process, currNode, nextNode, null);
    }
}